using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for BasePAge
/// </summary>
public abstract class BasePage : Page
{
    protected override void OnInit(EventArgs e)
    {
        if (acmsSite == null)
        {
            int siteId = 0;
            try
            {
                siteId = int.Parse(ConfigurationManager.AppSettings["SiteId"]);
            }
            catch (FormatException)
            {
            }
            catch (ArgumentNullException)
            {
            }
            
            acmsSite = Acms.Bll.Site.GetById(siteId);

            if (acmsSite == null)
            {
                if (!Page.Request.Url.AbsolutePath.EndsWith("/NoSite.aspx"))
                {
                    Response.Redirect("~/NoSite.aspx", true);
                }
            }
        }
        EnsureAccess();
        base.OnInit(e);
    }

    private static Acms.Bll.Site acmsSite;
    public static Acms.Bll.Site AcmsSite
    {
        get { return acmsSite; }
        set
        {
            if (value != null && value.Id >= 0)
            {
                acmsSite = value;
            }
        }
    }

    public abstract Acms.Bll.Role.Roles[] AllowedRoles{get;}

    private void EnsureAccess()
    {
        bool allowAnon = false;
        foreach (Acms.Bll.Role.Roles role in AllowedRoles)
        {
            if (role == Acms.Bll.Role.Roles.Anonomous)
            {
                allowAnon = true;
                break;
            }
        }
        if (!User.Identity.IsAuthenticated && !allowAnon)
        {
            FormsAuthentication.RedirectToLoginPage();
        }
        else if(!User.HasRole(AllowedRoles))
        {
            Server.Transfer("~/IncorrectRights.aspx");
        }
    }

    public new Acms.Bll.UserPrinciple User
    {
        get
        {
            return base.User as Acms.Bll.UserPrinciple;
        }
    }

    protected override object SaveViewState()
    {
        ViewState["PageTitle"] = Title;
        return base.SaveViewState();
    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        Title = ViewState["PageTitle"] as string;
    }
}
